package com.xcm.config;

import com.xcm.filter.SSOLoginFilter;
import com.xcm.queue.Receiver;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import javax.servlet.MultipartConfigElement;
import java.util.concurrent.CountDownLatch;

@Configuration
public class CustomConfig {
    /**
     * 自定义配置处理类
     */
    @Bean
    public CustomProperties customProperties() {
        return new CustomProperties();
    }

    /**
     * 配置文件上传大小限制
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大(MB)
        factory.setMaxFileSize("1024MB");
        // 设置总上传数据总大小(MB)
        factory.setMaxRequestSize("1024MB");
        return factory.createMultipartConfig();
    }

    /**
     * 配置单点登录过滤器
     */
    @Bean
    public FilterRegistrationBean ssoLoginFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new SSOLoginFilter());
        registration.addUrlPatterns("/*");
        registration.setName("ssoLoginFilter");
        return registration;
    }

    @Bean
    Receiver receiver(CountDownLatch latch) {
        return new Receiver(latch);
    }

    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("version"));

        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
}
